package cn.itcast.login;

import cn.itcast.base.BaseController;
import cn.itcast.dao.module.ModuleDao;
import cn.itcast.domain.module.Module;
import cn.itcast.domain.user.User;
import cn.itcast.service.system.UserService;
import cn.itcast.shiro.EasyTypeToken;
import cn.itcast.utils.commons.HttpUtils;
import cn.itcast.utils.commons.UtilFuns;
import com.alibaba.dubbo.config.annotation.Reference;
//import com.sun.net.httpserver.Authenticator.Result;
import javassist.expr.Expr;
import org.apache.commons.math3.analysis.function.Exp;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;
import java.util.Map;

@Controller
public class LoginController extends BaseController {
    @Autowired
    private UserService userService;

    private String appid = "wx3bdb1192c22883f3";
    private String secret = "db9d6b88821df403e5ff11742e799105";
    private String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";
    private String wxInfoUrl = "https://api.weixin.qq.com/sns/userinfo";

    /* @RequestMapping("/login")
     public String login(String email, String password) {

         if (UtilFuns.isEmpty(email) || UtilFuns.isEmpty(password)) {
             return "forward:/login.jsp";

         }
         User user = userService.findByEmail(email);
         if (user == null || !password.equals(user.getPassword())) {
             request.setAttribute("error", "用户名或密码错误");
             return "forward:/login.jsp";
         }
         // 将登陆用户存入session到页面展示
         session.setAttribute("loginUser", user);
         // 权限--判断当前登陆用户的不同级别做不用的菜单数据查询
         List<Module> menus = userService.findMenus(user);
         // 将查询到的用户权限菜单带到页面展示
         session.setAttribute("modules",menus);
         //只有成功了才到项目的主体页面
         return "home/main";
     }*/
    @RequestMapping("/login")
    public String login(String email, String password) {
        try {
            //1、获取subject对象
            Subject subject = SecurityUtils.getSubject();
            //2、 调用subject的login方法
            //UsernamePasswordToken token = new UsernamePasswordToken(email, password);

            EasyTypeToken token = new EasyTypeToken(email, password);
            subject.login(token);
            //3、登录成功的逻辑
            //从shiro中获取用户对象放入session中
            User user = (User) subject.getPrincipal();
            session.setAttribute("loginUser", user);
            //查询当前用户所具有的权限并返回给前段页面显示
            List<Module> menus = userService.findMenus(user);
            session.setAttribute("modules", menus);

        } catch (Exception e) {
            //登录失败的逻辑
            e.printStackTrace();
            request.setAttribute("error", "用户名或密码错误");
            return "forward:/login.jsp";
        }
        //只有成功了才到项目的主体页面
        return "home/main";
    }

    @RequestMapping(value = "/weixinlogin", name = "进入微信登录")
    public String weixinLogin(String code) {

        if (code == null) {
            System.out.println("未授权");
        }

        String atUtl = accessTokenUrl + "?code=" + code + "&appid=" + appid + "&secret=" + secret + "&grant_type=authorization_code";
        Map<String, Object> map1 = HttpUtils.sendGet(atUtl);

        Object access_token = map1.get("access_token");
        Object openid = map1.get("openid").toString();
        if (access_token == null && openid == null) {
            System.out.println("用户未登录...");
        }
        //2.根据access_token和openId获取微信用户信息

        String wxurl = wxInfoUrl + "?access_token=" + access_token + "&openid=" + openid;
        Map<String, Object> map2 = HttpUtils.sendGet(wxurl);
        Object unionid = map2.get("unionid");
        String unionid_s = unionid.toString();
        User user1 = userService.findByUnionid(unionid_s);
        if (user1 == null) {
            //微信绑定页面
            request.setAttribute("unionid", unionid_s);
            return "forward:email.jsp";
        }

/*
        UsernamePasswordToken token = new UsernamePasswordToken(user1.getEmail(), user1.getPassword());
*/
        //免密登录
        EasyTypeToken token = new EasyTypeToken(user1.getEmail());
        //获取主题
        Subject subject = SecurityUtils.getSubject();
        //开始认证
        subject.login(token);

        //从shiro中获取已认证的用户
       User user = (User) subject.getPrincipal();
        //把登录用户放入session
        session.setAttribute("loginUser",user);
        List<Module> moduleList = userService.findMenus(user);
        session.setAttribute("modules",moduleList);
        return "home/main";
    }



    @RequestMapping(value = "/log", name = "微信进入主页面")
    public String log() {
        return "home/main";
    }

    //微信登陆邮箱绑定
    @RequestMapping(value = "/emailAdd", name = "微信第一次扫码进入绑定邮箱页面")
    public String emailAdd(String email, String password, String unionid) {
        if (UtilFuns.isEmpty(email) || UtilFuns.isEmpty(password)) {
            request.setAttribute("unionid", unionid);
            request.setAttribute("error", "邮箱或密码不能为空");
            return "forward:email.jsp";
        }

       // password = new Md5Hash(password, email, 1).toString();
        System.out.println("绑定邮箱页面的密码 = " + password);
        //UsernamePasswordToken token = new UsernamePasswordToken(email, password);
        EasyTypeToken token = new EasyTypeToken(email, password);
        Subject subject = SecurityUtils.getSubject();

        //开始身份认证
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            request.setAttribute("error","邮箱或者密码错误");
            request.setAttribute("unionid",unionid);
            return "forward:email.jsp";
        }

        User userByEmail = userService.findByEmail(email);
        if (!UtilFuns.isEmpty(userByEmail.getWxunionid())) {
            request.setAttribute("error", "此邮箱已被绑定，请解绑后重试!");
            request.setAttribute("unionid", unionid);
            return "forward:email.jsp";
        }


        //登陆成功的逻辑
        //将微信用户保存
       // User wxUser = new User();
        //wxUser.setId(userByEmail.getId());
        userByEmail.setWxunionid(unionid);
        userService.update(userByEmail);
        //将用户信息放入session中
        User user =(User) subject.getPrincipal();
        User byId = userService.findById(user.getId());
        session.setAttribute("loginUser",byId);
        List<Module> modules = userService.findMenus(user);
        session.setAttribute("modules",modules);
        return "redirect:log.do";
    }


    @RequestMapping("/home")
    public String home() {
        return "home/home";
    }

    //退出
    @RequestMapping(value = "/logout", name = "用户登出")
    public String logout() {

        SecurityUtils.getSubject().logout();//登出
        return "forward:login.jsp";
    }


}
